package cn.lyq.card.ui.web

import android.content.Context
import android.content.Intent
import android.view.View
import android.webkit.WebView
import android.widget.LinearLayout
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.global.Const
import cn.lyq.card.utils.setClick
import com.just.agentweb.AgentWeb
import com.just.agentweb.WebChromeClient
import kotlinx.android.synthetic.main.act_web.*
import kotlinx.android.synthetic.main.layout_title.*

class WebActivity : BaseActivity() {

    companion object {
        private const val KEY_URL = "URL"

        @JvmStatic
        fun start(context: Context, url: String) {
            val starter = Intent(context, WebActivity::class.java)
                .putExtra(KEY_URL, url)
            context.startActivity(starter)
        }
    }

    private lateinit var mAgentWeb: AgentWeb
    private val url by lazy {
        intent.getStringExtra(KEY_URL)?.run {
            if (this.startsWith("http")) {
                this
            } else {
                "${Const.BASE_URL}${this}"
            }
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.act_web
    }

    override fun initView() {
        super.initView()
        tvTitleSplit.visibility = View.GONE
        val webChromeClient = object : WebChromeClient(){
            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                if (title != null && title.isNotEmpty()){
                    setMyTitle(title)
                }
            }
        }  
        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(groupWeb, LinearLayout.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .setWebChromeClient(webChromeClient)
            .createAgentWeb()
            .ready()
            .go(url)

    }

    override fun initListener() {
        super.initListener()
        imgBack.setClick {
            finish()
        }
    }

    override fun onBackPressed() {
        if (!mAgentWeb.back()) {
            super.onBackPressed()
        }
    }
}